package com.foreknow.controller;

import com.foreknow.bean.Admin;
import com.foreknow.service.AdminService;
import com.foreknow.service.impl.AdminServiceImpl;

import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置从服务器端向客户端返回的内容的类型   MIME类型：text/html
        resp.setContentType("text/html;charset=utf-8");
        //客户端向服务器端请求的编码格式(否则会产生乱码)  默认：iOS 8859-1
        req.setCharacterEncoding("UTF-8");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置从服务器端向客户端返回的内容的类型   MIME类型：text/html
        //resp.setContentType("text/html;charset=utf-8");
        //客户端向服务器端请求的编码格式(否则会产生乱码)  默认：iOS 8859-1
        //req.setCharacterEncoding("UTF-8");
        //获取到HttpSession对象用于保存用户的信息
        HttpSession session = req.getSession();
        //获取打印流用于向网页输出内容
        PrintWriter out = resp.getWriter();
        //获取请求参数  username = ? & password = ?
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //调用service中的方法
        AdminService adminService = new AdminServiceImpl();
        Admin admin = adminService.isCheckLogin(username,password);
        if (admin != null){
           // out.println(admin.getUsername()+"-----"+admin.getPassword());
            //如果登陆成功，就要将用户的信息保存到Session中
            session.setAttribute("username",admin.getUsername());
            //请求转发
            req.getRequestDispatcher("guestManager?q=list").forward(req,resp);
            //重定向
            //resp.sendRedirect("/list.jsp");

        } else {
            out.println("no admin...");
        }
    }
}
